﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;

namespace Silvermoon.OpenGL.Native
{
    internal static class SearchHelper
    {
        /// <summary>
        /// Performs a quick binary search for less or equal.
        /// </summary>
        public static int BinarySearchLeEq(Point point, IList<VectorQuads> values, int max)
        {
            max = Math.Min(max, values.Count);
            if (max == 0) return 0;
            int min = 0;
            int i = max >> 1;

            while (min < max)
            {
                var item = values[i];
                int dif = ComparePoint(point, item.GetRect());

                if (dif == 0) return i;
                if (dif < 0) min = i + 1;
                else max = i;
                i = (min + max) >> 1;
            }
            return i - 1;
        }

        private static int ComparePoint(Point point, Rectangle rect)
        {
            int y = point.Y;
            if (rect.Top > y) return 1;
            if (rect.Bottom < y) return -1;
            int x = point.X;
            if (rect.Left > x) return 1;
            if (rect.Right < x) return -1;
            return 0;
        }


    }
}
